package cn.lcl.filter;

import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by licho on 2017/8/17 0017.
 */

/**
 * 拦截所有的请求在请求被服务之前
 */
@WebFilter("/*")
public class ExceptionPreHandler implements Filter {
private static  final Logger log=Logger.getLogger(ExceptionPreHandler.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
            log.info("请求过滤器已启动");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)request;
        HttpServletResponse resp=(HttpServletResponse)response;
        //获取域名后得请求url
        try{
            chain.doFilter(request,response);
        }catch (Exception e){
            log.info("内部错误，返回主页");
            resp.sendRedirect(req.getContextPath()+"/400.jsp");
            log.error("异常拦截器消息:",e);
        }
    }

    @Override
    public void destroy() {
        log.info("请求过滤器已经销毁");
    }
}
